﻿using AutoMapper;
using Fonour.Application.Dtos;
using Fonour.Application.Mappers;
using Fonour.Application.Services.Interfaces;
using Fonour.Domain.Entities;
using Fonour.Domain.IRepositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fonour.Application.Services
{
    public class MenuAppService : ServiceBase<MenuDto, Menu>, IMenuAppService
    {
        private readonly IMenuRepository _menuRepository;
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;
        private readonly IMapper _mapper;

        public MenuAppService(IMenuRepository menuRepository, IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper) : base(menuRepository, mapper)
        {
            this._menuRepository = menuRepository;
            this._userRepository = userRepository;
            this._roleRepository = roleRepository;
            this._mapper = mapper;
        }

        /// <summary>
        /// 根据用户获取功能菜单
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public async Task<List<MenuDto>> GetMenusByUserAsync(Guid userId)
        {
            List<MenuDto> result = new List<MenuDto>();
            var allMenus = await _menuRepository.GetAllListAsync(it => it.Type == 0);
            if (userId == Guid.Empty) //超级管理员
                return this._mapper.Map<List<MenuDto>>(allMenus.OrderBy(it => it.SerialNumber));
            var user = await _userRepository.GetWithRolesAsync(userId);
            if (user == null)
                return result;
            var userRoles = user.UserRoles;
            List<Guid> menuIds = new List<Guid>();
            foreach (var role in userRoles)
            {
                menuIds = menuIds.Union(await _roleRepository.GetAllMenuListByRoleAsync(role.RoleId)).ToList();
            }

            allMenus = allMenus.Where(it => menuIds.Contains(it.Id)).OrderBy(it => it.SerialNumber).ToList();
            return this._mapper.Map<List<MenuDto>>(allMenus);
        }
    }
}
